package Sms

import (
	"encoding/json"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	console "github.com/alibabacloud-go/tea-console/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/pkg/errors"
	"mall-api-gin/pkg/setting"
)

type Aliyun struct {
}

func AliyunClient() SmsInterface {
	return Aliyun{}
}

//SEND_TYPE_LOGIN := map[string]interface{}{'tempId' : 'SMS_212875120', 'content' : '验证码${code}，您正在登录，若非本人操作，请勿泄露。'}

//SEND_TYPE_LOGIN  := ['tempId' => 'SMS_212875120', 'content' => '验证码${code}，您正在登录，若非本人操作，请勿泄露。']
//SEND_TYPE_CHANGE := ['tempId' => 'SMS_212875121', 'content' => '验证码${code}，您正在进行身份验证，打死不要告诉别人哦！']
//SEND_TYPE_WITHDRAWAL := ['tempId' => 'SMS_212875121', 'content' => '验证码${code}，您正在进行身份验证，打死不要告诉别人哦！']

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func CreateClient(accessKeyId *string, accessKeySecret *string) (client *dysmsapi20170525.Client, err error) {
	config := &openapi.Config{
		// 您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	client = &dysmsapi20170525.Client{}
	client, err = dysmsapi20170525.NewClient(config)
	return client, err
}

func (a Aliyun) Send(mobile string, smsCode string) (bool, error) {
	client, err := CreateClient(tea.String(setting.SmsSetting.AccessKeyId), tea.String(setting.SmsSetting.AccessKeySecret))
	if err != nil {
		return false, err
	}
	params := map[string]interface{}{"code": smsCode}
	paramsJson, err := json.Marshal(params)
	paramsData := string(paramsJson)
	fmt.Printf("参数信息：%v\n", paramsData)
	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(mobile),
		SignName:      tea.String(setting.SmsSetting.SignName),
		TemplateCode:  tea.String("SMS_212875120"),
		TemplateParam: &paramsData,
	}
	runtime := &util.RuntimeOptions{}
	resp, err := client.SendSmsWithOptions(sendSmsRequest, runtime)
	if err != nil {
		return false, err
	}
	fmt.Printf("发送短信信息：%v 类型：%T\n", resp, resp)
	data := tea.ToMap(resp)
	fmt.Printf("发送短信信息2：%v, Code = %v, Message = %v\n", data["body"], *resp.Body.Code, *resp.Body.Message)

	//code := data["body"].(map[string]interface{})["Code"]
	//message := data["body"].(map[string]interface{})["Message"]
	if *resp.Body.Code != "OK" {
		return false, errors.New(*resp.Body.Message)
	}
	console.Log(util.ToJSONString(tea.ToMap(resp)))
	return true, err
}
